package com.supcalls.atomic;

import java.util.concurrent.atomic.AtomicReference;

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "'}";
    }
}

public class AtomicReferenceDemo {
    public static void main(String[] args) {
        Person initialPerson = new Person("Alice");
        AtomicReference<Person> atomicPerson = new AtomicReference<>(initialPerson);

        // 创建多个线程来模拟并发环境
        Thread t1 = new Thread(() -> {
            Person currentPerson = atomicPerson.get();
            Person newPerson = new Person("Bob");
            boolean isUpdated = atomicPerson.compareAndSet(currentPerson, newPerson);
            System.out.println("Thread-1 CAS result: " + isUpdated + ", New value: " + atomicPerson.get());
        });

        Thread t2 = new Thread(() -> {
            Person currentPerson = atomicPerson.get();
            Person newPerson = new Person("Charlie");
            boolean isUpdated = atomicPerson.compareAndSet(currentPerson, newPerson);
            System.out.println("Thread-2 CAS result: " + isUpdated + ", New value: " + atomicPerson.get());
        });

        // 启动线程
        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 输出最终的对象
        System.out.println("Final value: " + atomicPerson.get());
    }
}

